package robot

import (
	"context"
	"sale-admin/config/mysql"
	"sale-admin/internal/app/grpc/client"
	"sale-admin/internal/app/grpc/protoc/system_admin"
	"sale-admin/internal/dal"
	"sale-admin/internal/dao"
	"sale-admin/internal/define"
	"sale-admin/internal/models"

	"192.168.1.75/go-pkg/errorx"
	"192.168.1.75/go-pkg/helper"
	"192.168.1.75/go-pkg/logx"
)

type RobotBackground struct{}

// List 背景图列表
func (RobotBackground) List(ctx context.Context,
	Page, Limit int,
	DefaultUse int,
	Name string,
	merchantID string,
) (
	list []models.MaGoodsBackground,
	count int64,
	err error,
) {
	db := mysql.NewDB()
	tx := db.Model(&models.MaGoodsBackground{})
	// 1. 检索活动名称
	if Name != "" {
		tx.Where("name like ?", "%"+Name+"%")
	}
	// 2. 检索活动状态
	if DefaultUse != 0 {
		tx.Where("default_use = ?", DefaultUse)
	}

	if merchantID != "1" {
		// 获取直系商户
		familyMerchants := []string{}
		cli, err1 := client.GetSystemAdminClient()
		if err1 != nil {
			return
		}
		rsp, err := cli.GetFamilyMerchants(ctx, &system_admin.FamilyMerchantsReq{MerchantId: merchantID})
		if err == nil && rsp != nil {
			familyMerchants = rsp.MerchantIds
		}
		tx.Where("merchant_id IN ?", familyMerchants)
	}

	tx.Count(&count)

	// 赋空值
	list = []models.MaGoodsBackground{}
	helper.Gorm{}.Paginate(tx, int(Page), int(Limit)).Find(&list)

	return
}

// 添加机器背景图
func (RobotBackground) Del(
	ctx context.Context,
	ID string,
) (
	err error,
) {
	db := mysql.NewDB()
	db.Model(&models.MaGoodsBackground{}).
		Where("id = ? and deleted_at = 0", ID).
		Delete(&models.MaGoodsBackground{})
	return
}

// 上架或下架背景图
func (RobotBackground) Set(
	ctx context.Context,
	id string,
	defaultUse int,
) (
	err error,
) {
	db := mysql.NewDB()
	if id != "" {
		// 编辑状态
		var data models.MaGoodsBackground
		// 查询信息
		db.Model(&models.MaGoodsBackground{}).Where("id = ?", id).Take(&data)
		if data.DefaultUse != defaultUse {
			data.DefaultUse = defaultUse
		}
		// 执行更新
		err = db.Model(&models.MaGoodsBackground{}).Where("id = ?", id).Updates(&data).Error
		if err != nil {
			err = errorx.New("更新失败", -1)
			return
		}
	}
	return
}

// 添加机器背景图
func (RobotBackground) Add(
	ctx context.Context,
	id,
	image string,
	defaultUse int,
	Name string,
	Position int,
	merchantID string,
) (
	err error,
) {
	db := mysql.NewDB()
	if id != "" {
		// 编辑
		var data models.MaGoodsBackground
		// 查询信息
		db.Model(&models.MaGoodsBackground{}).Where("id = ?", id).Take(&data)
		data.DefaultUse = defaultUse
		data.Name = Name
		data.Position = Position
		// 属于重新上传图片的情况，需要重新校验
		if image != "" && image != data.Image {
			// 2.图片提交时，需确认文件
			// 初始化
			SystemAdminClient, clientErr := client.GetSystemAdminClient()
			if clientErr != nil {
				err = clientErr
				return
			}
			// 开始确认文件
			var req system_admin.ConfirmFileReq
			req.FileUrl = image
			res, err1 := SystemAdminClient.ConfirmFile(context.Background(), &req)
			if err1 != nil && res.Code != 0 {
				logx.Error(context.Background(), "activity confirm file error", logx.Any("res", res), logx.Any("err", err1.Error()))
				return
			}
			data.Image = res.FileUrl
		}
		// 执行更新
		err = db.Model(&models.MaGoodsBackground{}).Where("id = ?", id).Updates(&data).Error
		if err != nil {
			err = errorx.New("更新失败", -1)
			return
		}
	} else {
		// 新增
		var data models.MaGoodsBackground
		data.DefaultUse = defaultUse
		data.Name = Name
		data.Position = Position
		data.MerchantID = merchantID
		if image != "" {
			// 2.图片提交时，需确认文件
			// 初始化
			SystemAdminClient, clientErr := client.GetSystemAdminClient()
			if clientErr != nil {
				err = clientErr
				return
			}
			// 开始确认文件
			var req system_admin.ConfirmFileReq
			req.FileUrl = image
			res, err1 := SystemAdminClient.ConfirmFile(context.Background(), &req)
			if err1 != nil && res.Code != 0 {
				logx.Error(context.Background(), "activity confirm file error", logx.Any("res", res), logx.Any("err", err1.Error()))
				return
			}
			data.Image = res.FileUrl
		}
		// 执行写入
		err = db.Model(&models.MaGoodsBackground{}).Create(&data).Error
		if err != nil {
			err = errorx.New("新增失败", -1)
			return
		}
	}

	return
}

// 获取机器背景图
func (RobotBackground) GetBackground(
	ctx context.Context,
	salesID string,
	Position int,
) (
	image string,
	err error,
) {
	robotDetail, _ := dao.Robot{}.RobotDetail(ctx, mysql.NewDB(), "", "", salesID)
	if robotDetail == nil {
		return "", nil
	}
	bgIDs, _ := dao.ObjAssociation{}.GetAssociationID(ctx, dal.Q, define.AssociationGoodsBGRobot, "", robotDetail.RobotName)
	if len(bgIDs) <= 0 {
		return "", nil
	}
	// 只返回有默认的图片，没有则随便选择一张
	db := mysql.NewDB()
	var info models.MaGoodsBackground
	tx := db.Model(&models.MaGoodsBackground{}).
		Where("default_use = ?", 1).
		Where("id IN ?", bgIDs)
	// 有传位置
	if Position > 0 {
		tx.Where("position = ?", Position)
	} else {
		tx.Where("position = ?", 1)
	}
	tx.Take(&info)
	if info.Image != "" {
		image = info.Image
	}
	return
}

// BindRobots 绑定设备
func (RobotBackground) BindSet(
	ctx context.Context,
	bgID string, // 背景id
	robotIDs []string, // 允许使用的机器
) error {
	// 删除旧的
	dao.ObjAssociation{}.Delete(ctx, dal.Q, define.AssociationGoodsBGRobot, bgID, "")
	// 设置可允许使用的机器
	if len(robotIDs) > 0 {
		// 增加新的
		records := []*models.MaObjAssociation{}
		for _, robotID := range robotIDs {
			records = append(records, &models.MaObjAssociation{
				AssociationType: int(define.AssociationGoodsBGRobot),
				ObjID:           bgID,
				AssociationID:   robotID,
			})
		}
		dao.ObjAssociation{}.Add(ctx, dal.Q, records, 200)
	}
	return nil
}

type BGBindSetttingT struct {
	RobotIDs []string `json:"robot_ids"`
}

// GetBindSetting 获取绑定设置
func (RobotBackground) GetBindSetting(
	ctx context.Context,
	bgID string, // 背景id
) (bindSetting BGBindSetttingT) {
	robotIDs, _ := dao.ObjAssociation{}.GetAssociationID(ctx, dal.Q, define.AssociationGoodsBGRobot, bgID, "")
	if robotIDs == nil {
		bindSetting.RobotIDs = []string{}
	} else {
		bindSetting.RobotIDs = robotIDs
	}
	return bindSetting
}
